using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using PersistenceObject.Framework.Expressions;
using System.Collections.ObjectModel;

namespace PersistenceObject.Framework
{
    internal class CommandBuilder
    {
        private const string SQL_DELETE = "DELETE FROM {0} ";
        private const string SQL_SELECT = "SELECT {0} FROM {1} ";
        private CommandBuilder() { }

        public static void AddCommandFilter(IDbDriver driver, IDbCommand comm, IExpression exp)
        {
            if (exp != null)
            {
                string filter = exp.GetFilter(driver);
                if ((filter != null) && (filter.Trim() != ""))
                {
                    comm.CommandText = comm.CommandText + " WHERE " + filter;
                }
                Collection<FieldValue> collection = exp.GetDataParams(driver);
                if (collection != null && collection.Count > 0)
                {
                    foreach (FieldValue value in collection)
                    {
                        comm.Parameters.Add(driver.GetParameter(value.Name, value.Value));
                    }
                }
                Expression.DoClear();
                exp.ClearParams();
            }
        }

        public static IDbCommand Delete(IDbDriver driver, string tableName, IExpression exp)
        {
            IDbCommand comm = driver.GetCommand();
            comm.CommandText = string.Format(SQL_DELETE, tableName);
            CommandBuilder.AddCommandFilter(driver, comm, exp);
            return comm;
        }

        public static IDbCommand Query(IDbDriver driver, string table, IExpression exp)
        {
            return CommandBuilder.Query(driver, table, "*", exp);
        }

        public static IDbCommand Query(IDbDriver driver, string table, string fields, IExpression exp)
        {
            IDbCommand comm = driver.GetCommand();
            comm.CommandText = string.Format(SQL_SELECT, fields, table);
            CommandBuilder.AddCommandFilter(driver, comm, exp);
            return comm;
        }
    }
}
